package org.example.springmvcdemo.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RestController
@RequestMapping("/session")
public class SessionController {
    @RequestMapping("/getC")
    public String getCokkie(HttpServletRequest request, HttpServletResponse response){
        //获取参数  可以获取到所有的cookie
        //String name = request.getParameter("name");
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            Arrays.stream(cookies).forEach(ck-> System.out.println(ck.getName()+":"+ck.getValue()));
        }
        return "获取cookie";
    }
    //注解的方式获取cookie 获取到一个cookie
    @RequestMapping("/getC2")
    public String getCokkie2(@CookieValue("bite") String bite){
        return "从Cookie中获取值,Cookie:"+bite;
    }

    //创建session
    @RequestMapping("/setSess")
    public String setSession(HttpServletRequest request){
        //从cookie中获取到了sessionID，根据sessiosID获取session对象
        HttpSession session = request.getSession();
        session.setAttribute("name","zhangsan");
        return "设置session成功";
    }
    //获取session
    @RequestMapping("/getSess")
    public String getSession(HttpServletRequest request){
        //从cookie中获取到了sessionID，根据sessiosID获取session对象
        HttpSession session = request.getSession();
        String name = (String)session.getAttribute("name");
        return "从session中获取name:"+name;
    }
    @RequestMapping("/getSess2")
    public String getSession2(HttpSession session){
        String name = (String)session.getAttribute("name");
        return "从session中获取name:"+name;
    }
    @RequestMapping("/getSess3")
    public String getSession3(@SessionAttribute("name") String name){
        //String name = (String)session.getAttribute("name");
        return "从session中获取name:"+name;
    }
    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        return "从header中获取信息，userAgent:"+userAgent;
    }
    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent){
        return "从header中获取信息，header:"+userAgent;
    }
}
